﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;

namespace FCNS.Windows
{
    /// <summary>
    /// Windows 桌面
    /// </summary>
    public class Desktop
    {
        /// <summary>
        /// 更改 Windows 桌面墙纸 : XP 系统
        /// </summary>
        /// <param name="img">墙纸图片路径</param>
        /// <param name="screen">是否自动选择墙纸样式</param>
        public void DesktopImage(Bitmap img,string screen)
        {
            const int SPI_SETDESKWALLPAPER = 20;
            const int SPIF_UPDATEINIFILE = 0x01;
            const int SPIF_SENDWININICHANGE = 0x02;
          Bitmap newImg = null;
                if (screen != "3")
                {
                    newImg = new Bitmap(img, img.Width, img.Height);
                }
                else
                {
                    
                    if (img.Width > System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width * 3 / 4 && img.Height > System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height * 3 / 4)
                    {
                        newImg = new Bitmap(img, FCNS.WinApi.GetSystemMetrics(0), FCNS.WinApi.GetSystemMetrics(1));
                    }
                    else
                    {
                        Microsoft.Win32.Registry.SetValue(@"HKEY_CURRENT_USER\Control Panel\Desktop", "WallpaperStyle", "0", Microsoft.Win32.RegistryValueKind.String);
                        newImg = new Bitmap(img, img.Width, img.Height);
                    }
                }
                String filename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
                    + "\\Wallpaper.bmp";

                newImg.Save(filename, System.Drawing.Imaging.ImageFormat.Bmp);

                FCNS.WinApi.SystemParametersInfo(SPI_SETDESKWALLPAPER, 0,
                    filename,
                    SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
                newImg.Dispose();
        }

        /// <summary>
        /// 获取指定标题的窗体
        /// </summary>
        /// <param name="formText">标题包含的字符</param>
        /// <returns>句柄列表</returns>
        public static List<IntPtr> GetIntPtr(string formText)
        {
            List<IntPtr> ptr = new List<IntPtr>();
            StringBuilder sb = new StringBuilder(255);
            IntPtr temp, form;
            temp = form = WinApi.GetDesktopWindow();
            form = WinApi.GetWindow(form, WinApi.GetWindow_Cmd.GW_CHILD);
            while (temp != form)
            {
                temp = form;
                WinApi.GetWindowText(form, sb, 255);
                if (sb.ToString().Contains(formText))
                {
                    ptr.Add(form);
                }
                form = WinApi.GetWindow(form, WinApi.GetWindow_Cmd.GW_HWNDNEXT);
            }
            return ptr;
        }
    }
}
